package com.pnemec.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ConfigurationReader {
	private String path = null;
	private Document document = null;

	public ConfigurationReader(String path) {
		this.path = path;
		init();
	}

	public void init() {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

		DocumentBuilder builder;
		try {
			builder = factory.newDocumentBuilder();
			BufferedInputStream stream = new BufferedInputStream(getClass()
					.getResourceAsStream(path));
			document = builder.parse(stream);
		} catch (ParserConfigurationException e) {
			System.out
					.println("ConfigurationReader.init(): cannot parse document: "
							+ e.getMessage());

		} catch (SAXException e) {
			System.out
					.println("ConfigurationReader.init(): cannot parse document (SAX exeption): "
							+ e.getMessage());
		} catch (IOException e) {
			System.out.println("ConfigurationReader.init(): cannot open file: "
					+ (this.path == null ? "null" : this.path) + ", message: "
					+ e.getMessage());
			e.printStackTrace();
		}

	}

	public Collection getAvailableLocale() {
		LinkedList reti = null;

		if (document == null)
			return null;
		NodeList list = document.getElementsByTagName("help");

		if ((list != null) && (list.getLength() > 0))
			reti = new LinkedList();

		for (int i = 0; i < list.getLength(); i++) {
			Node node = list.item(i);
			NamedNodeMap attrs = node.getAttributes();
			Node n = attrs.getNamedItem("locale");
			if (n != null) {
				String value = n.getNodeValue();
				if (value != null)
					reti.add(value);

			}
		}
		return reti;
	}

	/**
	 * get default locale
	 */
	public String getHelpString() {
		return getHelpString("default");
	}

	public String getHelpString(String locale) {
		if (document == null)
			return null;
		String searchFor = null;
		if (locale == "default") {
			searchFor = "default";
			locale = "true";
		} else
			searchFor = "locale";

		NodeList list = document.getElementsByTagName("help");

		for (int i = 0; i < list.getLength(); i++) {
			Node n = list.item(i).getAttributes().getNamedItem(searchFor);
			if ((n != null) && (n.getNodeValue().compareTo(locale) == 0)) {
				NodeList children = list.item(i).getChildNodes();
				for (int j = 0; j < children.getLength(); j++) {
					if (children.item(j).getNodeName() == "text") {
						return children.item(j).getTextContent();
					}
				}
			}
		}
		return null;

	}



}

